<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="关联用户id" prop="userId">
        <el-input
          v-model="queryParams.userId"
          placeholder="请输入关联用户id"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="日期" prop="reservationDate">
        <el-date-picker clearable
          v-model="queryParams.reservationDate"
          type="date"
          value-format="yyyy-MM-dd"
          placeholder="请选择日期">
        </el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['system:violation:remove']"
        >删除</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="violationList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="id" align="center" prop="id" />
      <el-table-column label="用户" align="center" prop="userName" />
      <el-table-column label="扣除信誉分值" align="center" prop="deductedScore" />
      <!-- 在表格列中增加状态格式化显示 -->
      <el-table-column label="申诉状态" align="center">
        <template slot-scope="scope">
          <span>{{ formatAppealStatus(scope.row.appealStatus) }}</span>
        </template>
      </el-table-column>


      <el-table-column label="申诉时间" align="center" prop="appealTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.appealTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="申诉原因" align="center" prop="appealReason" />
      <el-table-column label="预约id" align="center" prop="reservationId" />
      <el-table-column label="座位" align="center" prop="seatNumber" />
      <el-table-column label="自习室" align="center" prop="roomName" />
      <el-table-column label="时间段" align="center">
          <template slot-scope="scope">
            <span>{{ formatTimeSlot(scope.row.timeSlot) }}</span>
          </template>
      </el-table-column>
      <el-table-column label="预约日期" align="center" prop="reservationDate" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.reservationDate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
    <template slot-scope="scope">
      <!-- 状态0：取消违规 -->
      <el-button
        v-if="scope.row.appealStatus === 0"
        size="mini"
        type="text"
        icon="el-icon-close"
        @click="handleCancelViolation(scope.row)"
        v-hasPermi="['system:violation:cancel']"
      >取消违规</el-button>

      <!-- 状态1：申诉通过/驳回 -->
      <template v-if="scope.row.appealStatus === 1">
        <el-button
          size="mini"
          type="text"
          icon="el-icon-check"
          @click="handleCancelViolation(scope.row)"
        >申诉通过</el-button>
        <!-- bukofen -->
        <el-button
          size="mini"
          type="text"
          icon="el-icon-close"
          @click="handleCancelApproval(scope.row)"
        >驳回申诉</el-button>
      </template>

      <!-- 状态2/3：取消通过 -->
       <!-- kofen -->
      <el-button
        v-if="[2].includes(scope.row.appealStatus)"
        size="mini"
        type="text"
        icon="el-icon-refresh-left"
        @click="handleReject(scope.row)"
      >取消通过</el-button>

      <el-button
        v-if="[3].includes(scope.row.appealStatus)"
          size="mini"
          type="text"
          icon="el-icon-check"
          @click="handleCancelViolation(scope.row)"
        >申诉通过</el-button>
    </template>
  </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改违规处理对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listViolation, getViolation, delViolation, addViolation, updateViolation } from "@/api/system/violation";
import { importUncheckedToViolation, updateViolationStatus, rejectViolation } from "@/api/system/violation";
import { getRoomListAPI, getRoomInfoAPI } from "@/api/resource/room";
import { getSeatInfoAPI } from "@/api/resource/seat";
import { getUser } from "@/api/system/user";

export default {
  name: "Violation",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 违规处理表格数据
      violationList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        userId: null,
        appealStatus: null,
        reservationDate: null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        userId: [
          { required: true, message: "关联用户id不能为空", trigger: "blur" }
        ],
        deductedScore: [
          { required: true, message: "扣除信誉分值不能为空", trigger: "blur" }
        ],
        appealStatus: [
          { required: true, message: "申诉状态不能为空", trigger: "change" }
        ],
        reservationId: [
          { required: true, message: "预约id不能为空", trigger: "blur" }
        ],
        seatId: [
          { required: true, message: "座位id不能为空", trigger: "blur" }
        ],
        roomId: [
          { required: true, message: "房间id不能为空", trigger: "blur" }
        ],
        timeSlot: [
          { required: true, message: "时间段不能为空", trigger: "blur" }
        ],
        reservationDate: [
          { required: true, message: "预约日期不能为空", trigger: "blur" }
        ]
      }
    };
  },
  created() {
    this.getList();
    importUncheckedToViolation()
  },
  methods: {
// 格式化申诉状态
formatAppealStatus(status) {
    const statusMap = {
      0: '未申请',
      1: '申诉中',
      2: '申诉通过',
      3: '已驳回'
    }
    return statusMap[status] || '未知状态'
  },
  
  // 格式化时间段
  formatTimeSlot(slot) {
    const slotMap = {
      1: '早上',
      2: '中午',
      3: '下午'
    }
    return slotMap[slot] || '未知时段'
  },

  async getList() {
  this.loading = true;
  try {
    const response = await listViolation(this.queryParams);
    // 等待数据丰富完成后再更新表格
    this.violationList = await this.enrichViolationData(response.rows);
    this.total = response.total;
  } catch (error) {
    console.error("数据加载失败:", error);
    this.$modal.msgError("数据加载失败: " + (error.message || error));
    // 失败时显示原始ID
    this.violationList = response?.rows?.map(item => ({
      ...item,
      userName: `用户${item.userId}`,
      roomName: `自习室${item.roomId}`,
      seatNumber: `座位${item.seatId}`
    })) || [];
  } finally {
    this.loading = false;
  }
},
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        userId: null,
        deductedScore: null,
        appealStatus: null,
        appealTime: null,
        appealReason: null,
        reservationId: null,
        seatId: null,
        roomId: null,
        timeSlot: null,
        reservationDate: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加违规处理";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getViolation(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改违规处理";
      });
    },
    /**
     * 
     * @param row 违规处理数据
     */
    handleCancelViolation(row){
      console.log(Number(row.id))
      this.$modal.confirm('是否确认取消违规处理编号为"' + row.id + '"的数据项？').then(function() {
        return updateViolationStatus(row.id, row.userId, 2);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("取消成功");
      }).catch(() => {});
    },
    /**
     * 
     * @param row 违规处理数据
     */
    handleCancelApproval(row){
      console.log(Number(row.id))
      this.$modal.confirm('是否确认取消通过编号为"' + row.id + '"的数据项？').then(function() {
        return updateViolationStatus(row.id, row.userId, 3);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("取消成功");
      }).catch(() => {});
    },
    handleReject(row){
      console.log(Number(row.id))
      this.$modal.confirm('是否确认驳回编号为"' + row.id + '"的数据项？').then(function() {
        return rejectViolation(row.id, row.userId);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("驳回成功");
      }).catch((e) => {
        console.log(e)
      });
    },


    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateViolation(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addViolation(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除违规处理编号为"' + ids + '"的数据项？').then(function() {
        return delViolation(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('system/violation/export', {
        ...this.queryParams
      }, `violation_${new Date().getTime()}.xlsx`)
    },

    /** 丰富预约数据，添加关联信息 */
    async enrichViolationData(violations) {
      // 使用Promise.all并行获取所有关联信息
      return Promise.all(
        violations.map(async (item) => {
          try {
            // 并行获取自习室和座位信息
            const [roomRes, seatRes, userRes] = await Promise.all([
              getRoomInfoAPI(item.roomId).catch(() => ({ data: {} })),
              getSeatInfoAPI(item.seatId).catch(() => ({ data: {} })),
              getUser(item.userId).catch(() => ({ data: {} })),
            ]);

            return {
              ...item,
              roomName: roomRes.data?.name || "未知自习室",
              seatNumber: seatRes.data?.number || "未知座位",
              userName: userRes.data?.userName || "未知用户",
              // 如果还需要其他字段可以继续添加
            };
          } catch (error) {
            console.error(`获取关联信息失败(ID:${item.id}):`, error);
            return {
              ...item,
              roomName: "加载失败",
              seatNumber: "加载失败",
              userName: "加载失败",
            };
          }
        })
      );
    },

  }
};
</script>
